
import wx

import ab_document
import ab_executor
import ab_file
import ab_error
import ab_plx_viewer

from ab_exceptions import AofException


class PlxFileViewerFrame(ab_plx_viewer.NormalViewerFrame):
    def __init__(self, parent, app, handler, filename, title='',
                 plxs=None, *args, **kws):
        app.info('<PlxEditorFileFrame.__init__> Enter')

        ab_plx_viewer.NormalViewerFrame.__init__(self, parent, app, handler,
                                                 filename, title,
                                                 inherited=True)

        if isinstance(filename, ab_file.File):
            afile = filename
        else:
            afile = ab_file.File(app, filename, 'rb')

        # don't parse empty data
        if afile is None:
            wx.MessageBox('The temporary file could not be created'
                          'Error', wx.OK | wx.CENTRE | wx.ICON_ERROR)
        else:
            executor = ab_executor.Executor(self, app)
            if plxs is not None:
                ret = executor.run(afile, title,
                                   plxs=plxs,
                                   *args, **kws)
            else:
                ret = executor.run(afile, title, *args, **kws)

            if ret:
                self.displayDoc(executor)
            else:
                error = executor.getError()
                if error is not None:
                    dialog = ab_error.ErrorDialog(self.parent, error)
                    dialog.CenterOnScreen()
                    dialog.ShowModal()

        app.info('<PlxFileViewerFrame.__init__> Exit')


class PlxFileViewerDocHandler(ab_document.DocumentHandler):
    def __init__(self):
        ab_document.DocumentHandler.__init__(self, 'plx_viewer',
                                             PlxFileViewerFrame)


class PlxEditorViewerFrame(PlxFileViewerFrame):
    def __init__(self, parent, app, handler, title, data=None,
                 plxs=None, afile=None, *args, **kws):
        app.info('<PlxEditorFileFrame.__init__> Enter')
        if data is not None:
            temp = ab_file.File(app, None, 'ab+', data=data)

            PlxFileViewerFrame.__init__(self, parent, app, handler, temp,
                                        title, plxs, *args, **kws)
        elif afile is not None:
            PlxFileViewerFrame.__init__(self, parent, app, handler, afile,
                                        title, plxs, *args, **kws)
        else:
            raise AofException('PlxEditorViewerFrame', 'Parameter is missed')

        app.info('<PlxEditorFileFrame.__init__> Exit')


class PlxEditorViewerDocHandler(ab_document.DocumentHandler):
    def __init__(self):
        ab_document.DocumentHandler.__init__(self, 'plx_cnt_viewer',
                                             PlxEditorViewerFrame, True, False)
